<?php

namespace App\Models\Plane\Cities\Repositories;

use App\Models\Plane\Cities\PlaneCity;
use App\Models\Plane\Cities\Repositories\Interfaces\PlaneCityRepositoryInterface;
use App\Trip\Repository\BaseRepository;
use Illuminate\Support\Facades\Cache;

class PlaneCityRepository extends BaseRepository implements PlaneCityRepositoryInterface
{
    public function __construct(PlaneCity $model)
    {
        parent::__construct($model);
    }

    public function addCity(array $data): PlaneCity
    {
        if ($city = $this->findOneByCode($data['code'])) {
            $this->update($data, $city);
            return $city;
        }
        return $this->create($data);
    }

    public function findOneByCode(string $city_code): ?PlaneCity
    {
        $cache_key_code = "PlaneCities:Code:{$city_code}";
        if (Cache::has($cache_key_code)) {
            return Cache::get($cache_key_code);
        }
        $city = $this->findOneBy([
            'code' => $city_code,
        ]);

        Cache::put($cache_key_code, $city, config('trip.ttl.day') * 30);
        return $city;

    }

    public function delByCode(string $city_code): bool
    {
        return $this->findOneByCode($city_code)?->delete() ?: false;
    }

    public function findOneByName(string $city_name): ?PlaneCity
    {
        return $this->findOneBy([
            'name' => $city_name,
        ]);
    }

    public function findOneByAdCode(string $adcode): ?PlaneCity
    {
        return $this->findOneBy([
            'adcode' => $adcode,
        ]);
    }
}